﻿using System;
using Microsoft.EntityFrameworkCore;


namespace Code.Entity
{
    public class CodeAPPContext : DbContext
    {
        public CodeAPPContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<Admin> Admins { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<AdminRole> AdminRoles { get; set; }
        public DbSet<Menu> Menus { get; set; }
        public DbSet<MenuRole> MenuRoles { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            const string TablePrefix = "ce_";
            modelBuilder.Entity<Admin>(action => {
                action.ToTable(TablePrefix + nameof(Admin));
                action.HasKey(a => a.AdminId);
                action.Property(m => m.UserName).HasMaxLength(50).IsRequired();
                action.Property(m => m.Password).HasMaxLength(50).IsRequired();
                action.Property(m => m.Avatar).HasMaxLength(100);
                action.Property(m => m.LastLoginIP).HasMaxLength(10);
                action.Property(m => m.CreateTime).IsRequired();
            });

            modelBuilder.Entity<Role>(action => {
                action.ToTable(TablePrefix + nameof(Role));
                action.HasKey(a => a.RoleId);
                action.Property(m => m.RoleName).HasMaxLength(50).IsRequired();
                action.Property(m => m.CreateTime).IsRequired();
            });

            modelBuilder.Entity<AdminRole>(action => {
                action.ToTable(TablePrefix + nameof(AdminRole));
                action.HasKey(a => a.Id);
                //action.HasOne<Admin>().WithMany().HasForeignKey(m => m.AdminId);
                action.HasOne<Role>().WithMany().HasForeignKey(m => m.RoleId);
            });

            modelBuilder.Entity<Menu>(action => {
                action.ToTable(TablePrefix + nameof(Menu));
                action.HasKey(a => a.MenuId);
                action.Property(m => m.MenuName).HasMaxLength(50).IsRequired();
                action.Property(m => m.Icon).HasMaxLength(50);
                action.Property(m => m.Route).HasMaxLength(50);
                action.Property(m => m.ComponentPath).HasMaxLength(50);
                action.Property(m => m.CreateByName).HasMaxLength(50);
            });

            modelBuilder.Entity<MenuRole>(action =>
            {
                action.ToTable(TablePrefix + nameof(MenuRole));
                action.HasOne<Role>().WithMany().HasForeignKey(m => m.RoleId);
                action.HasOne<Menu>().WithMany().HasForeignKey(m => m.MenuId);
            });
        }
    }
}
